package ui.panel;

import cerebrum.common.EmptyChecker;
import cerebrum.common.FileUtil;
import cerebrum.controller.wallpaper.WallpaperCerebrum;
import com.alibaba.fastjson.JSONArray;
import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Paint;
import javafx.stage.DirectoryChooser;
import javafx.stage.StageStyle;
import javafx.util.Duration;
import ui.factory.SingletonFactory;
import ui.util.MySystemTray;
import ui.util.Window;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SetUpStage extends Window {
    private static SetUpStage instance = null;

    //调用单例工厂
    public static SetUpStage getInstance() {
        if (instance == null) {
            instance = SingletonFactory.getWeakInstace(SetUpStage.class);
        }
        return instance;
    }

    public SetUpStage() throws IOException {
        URL resource = getClass().getResource("/fxml/SetUp.fxml");
        root = FXMLLoader.load(resource);
        Scene scene = new Scene(root, 815, 497);
        scene.setFill(Paint.valueOf("#ffffff00"));
        //最小化到托盘
        MySystemTray.getInstance().listen(this);

        initStyle(StageStyle.TRANSPARENT);
        setScene(scene);
        setTitle("IceoLogy壁纸");

        ((Button) $("close")).setTooltip(new Tooltip("关闭"));
        ((Button) $("mini")).setTooltip(new Tooltip("最小化"));
        //设置提示延迟出现时间
        ((Button) $("close")).getTooltip().setShowDelay(Duration.millis(200));
        ((Button) $("mini")).getTooltip().setShowDelay(Duration.millis(200));
        move();
        myclose();
        mini();
        setIcon();

        exec();
    }

    /**
     * 关闭和最小化
     */
    public void myclose() {
        ((Button) $("close")).setOnAction(event -> this.close());
    }


    public void mini() {
        ((Button) $("mini")).setOnAction(event -> setIconified(true));
    }


    /**
     * 设置错误提示
     *
     * @param id
     * @param text
     */
    public void setErrorTip(String id, String text) {
        ((Label) $(id)).setText(text);
    }


    public void clear(String id) {
        ((TextField) $(id)).clear();
    }

    /**
     * 实现各个页面的交互，实现最终程序的运行
     */
    public void exec() {
        wallpaperTypeMessage();
        refreshFrequency();
        isCleaningImages();
        imagesUpdateDate();
        screenSaverSetUp();
        selectFolder();
        setUpExec();
        wallpaperTypePadding();
//        processControl();
    }

    //---------------------------- 设置界面 数据提交----------------------------
    private void processControl(){
        ((Pane) $("user_value")).setVisible(false);
    }
    private void wallpaperTypeChecked() {
        //设置提示
        setErrorTip("wallpaper_type_message", "              壁纸类型请至少选中两项");
        //设置提示颜色
        ((Label) $("wallpaper_type_message")).setTextFill(Paint.valueOf("#DC381F"));
        //设置不在隐藏
        ((Label) $("wallpaper_type_message")).setVisible(true);
        ((Label) $("wallpaper_type_message")).setManaged(true);


    }
    private void wallpaperTypePadding(){
        FlowPane wallpaperType = ((FlowPane)$("wallpaper_type"));
        wallpaperType.setHgap(20.0);
        wallpaperType.setVgap(8.0);
    }

    /**
     * 设置界面的运行
     */
    public void setUpExec() {
        ((Button) $("enter")).setOnAction(event -> {
            //用户选择的壁纸喜好
            JSONArray likeTypes = userLikeWallpaperType();
            if (EmptyChecker.isEmpty(likeTypes)) {
                return;
            }
            //壁纸保存路径
            String folderPath = ((Label) $("select_folder_path")).getText();
            if (EmptyChecker.isEmpty(folderPath)||folderPath.contains("请先选择壁纸路径!")) {
                String str = "请先选择壁纸路径!";
                setFolderStyle(str, "#FF6347", "选择保存路径");
                return;
            }
            //屏保
            int screenSaverValue = getScreenSaverValue();
            //壁纸刷新频率
            int refreshFrequencyValue = getRefreshFrequencyValue();
            //壁纸下载量
            long imagesDownloadNum = imagesDownloadNum();
            //是否清除下载的壁纸
            int cleaningImagesValue = isCleaningImagesValue();
            //壁纸更新时间
            int imagesUpdateDateValue = imagesUpdateDateValue();

            //配置持久化
            setUpSaveFile(likeTypes,
                    refreshFrequencyValue,
                    imagesDownloadNum,
                    cleaningImagesValue,
                    imagesUpdateDateValue,
                    folderPath, screenSaverValue);
        });
    }

    //设置持久化
    private void setUpSaveFile(JSONArray likeTypes,
                               int refreshFrequencyValue,
                               long imagesDownloadNum,
                               int cleaningImagesValue,
                               int imagesUpdateDateValue,
                               String folderPath,
                               int screenSaverValue) {
        Map obj = new HashMap<String, Object>();
        obj.put("is_user_set_up", true);
        obj.put("likeType", likeTypes);
        obj.put("frequency", refreshFrequencyValue * 1000);
        obj.put("downloadNum", imagesDownloadNum);
        obj.put("isCleaningImages", cleaningImagesValue);
        obj.put("updateImagesDate", imagesUpdateDateValue * 60);//分钟转化成秒
        obj.put("wallpaperFilePath", folderPath);
        obj.put("screenSaver", screenSaverValue);

        //将用户设置写入设置文件持久化
        FileUtil.writeFunctionRecord(obj);
        hide();
        //开始下载壁纸
        new Thread(new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                //后台程序开始运行
                WallpaperCerebrum.startRun(true);
                return null;
            }

        }).start();
    }

    /**
     * user Choose Like Wallpaper Type
     */
    private JSONArray userLikeWallpaperType() {
        boolean wallpaperTypeBing = ((CheckBox) $("wallpaper_type_bing")).isSelected();
        boolean wallpaperTypeComic = ((CheckBox) $("wallpaper_type_comic")).isSelected();
        boolean wallpaperTypeScenery = ((CheckBox) $("wallpaper_type_scenery")).isSelected();
        boolean wallpaperTypeBeauty = ((CheckBox) $("wallpaper_type_beauty")).isSelected();
        boolean wallpaperTypeModern = ((CheckBox) $("wallpaper_type_modern")).isSelected();
        boolean wallpaperTypeQuadraticElementBeauty = ((CheckBox) $("wallpaper_type_quadratic_element_beauty")).isSelected();
        boolean wallpaperTypeSexy = ((CheckBox) $("wallpaper_type_sexy")).isSelected();
        boolean wallpaperTypePets = ((CheckBox) $("wallpaper_type_pets")).isSelected();
        boolean wallpaperTypeRandom = ((CheckBox) $("wallpaper_type_random")).isSelected();
        boolean wallpaperTypeActors = ((CheckBox) $("wallpaper_type_actors")).isSelected();
        JSONArray likeTypes = new JSONArray();
        if (wallpaperTypeRandom) { //至少选中两项,选择了系统随机除外
            likeTypes.add("random");
            return likeTypes;
        }

        if (wallpaperTypeBing) {
            likeTypes.add("bing");
        }
        if (wallpaperTypeComic) {
            likeTypes.add("comic");
        }
        if (wallpaperTypeScenery) {
            likeTypes.add("scenery");
        }
        if (wallpaperTypeBeauty) {
            likeTypes.add("beauty");
        }
        if (wallpaperTypeModern) {
            likeTypes.add("modern");
        }
        if (wallpaperTypeQuadraticElementBeauty) {
            likeTypes.add("quadratic_element_beauty");
        }
        if (wallpaperTypeSexy) {
            likeTypes.add("sexy");
        }
        if (wallpaperTypePets) {
            likeTypes.add("pets");
        }
        if (wallpaperTypeActors){
            likeTypes.add("actors");
        }
        //选择不能低于两项
        if (likeTypes.size() < 2) {
            wallpaperTypeChecked();
            return new JSONArray();
        }
        return likeTypes;
    }

    //获取刷新频率用户选中了哪一个
    private int getRefreshFrequencyValue() {
        boolean refreshFrequency3 = ((RadioButton) $("refresh_frequency_3")).isSelected();
        boolean refreshFrequency5 = ((RadioButton) $("refresh_frequency_5")).isSelected();
        boolean refreshFrequency10 = ((RadioButton) $("refresh_frequency_10")).isSelected();
        boolean refreshFrequency30 = ((RadioButton) $("refresh_frequency_30")).isSelected();

        if (refreshFrequency3) {
            return 3;
        } else if (refreshFrequency5) {
            return 5;
        } else if (refreshFrequency10) {
            return 10;
        } else if (refreshFrequency30) {
            return 30;
        }
        return 0;
    }

    //获取壁纸下载量
    private long imagesDownloadNum() {
        double downloadNum = ((Slider) $("download_num")).getValue();
        return Math.round(downloadNum);
    }

    /**
     * 获取用户设置的多久清除一次下载的壁纸
     */
    private int isCleaningImagesValue() {
        boolean cleaningImagesNo = ((RadioButton) $("cleaning_images_no")).isSelected();
        boolean cleaningImagesLastTime = ((RadioButton) $("cleaning_images_last_time")).isSelected();
        boolean cleaningImagesThree = ((RadioButton) $("cleaning_images_three")).isSelected();
        boolean cleaningImagesTen = ((RadioButton) $("cleaning_images_ten")).isSelected();
        if (cleaningImagesNo) {
            return 0;
        } else if (cleaningImagesLastTime) {
            return 1;
        } else if (cleaningImagesThree) {
            return 3;
        } else if (cleaningImagesTen) {
            return 5;
        }
        return 0;
    }

    /**
     * 获取用户选择的壁纸更新时间
     */
    private int imagesUpdateDateValue() {
        boolean imagesUpdateDateFive = ((RadioButton) $("images_update_date_five")).isSelected();
        boolean imagesUpdateDateTen = ((RadioButton) $("images_update_date_ten")).isSelected();
        boolean imagesUpdateDateFifteen = ((RadioButton) $("images_update_date_fifteen")).isSelected();
        boolean imagesUpdateDateThirty = ((RadioButton) $("images_update_date_thirty")).isSelected();
        if (imagesUpdateDateFive) {
            return 5;
        } else if (imagesUpdateDateTen) {
            return 10;
        } else if (imagesUpdateDateFifteen) {
            return 15;
        } else if (imagesUpdateDateThirty) {
            return 30;
        }
        return 0;
    }

    private int getScreenSaverValue() {
        boolean screenSaverNo = ((RadioButton) $("screenSaver_no")).isSelected();
        boolean screenSaverOne = ((RadioButton) $("screenSaver_one")).isSelected();
        boolean screenSaverThree = ((RadioButton) $("screenSaver_three")).isSelected();
        boolean screenSaverFive = ((RadioButton) $("screenSaver_five")).isSelected();
        if (screenSaverNo) {
            return 0;
        } else if (screenSaverOne) {
            return 60;

        } else if (screenSaverThree) {
            return 180;
        } else if (screenSaverFive) {
            return 300;
        }
        return 0;
    }

    //--------------------------------- 页面联动控制----------------------------------------------
    //写真勾选警告提示
    private void wallpaperTypeMessage() {
        ((CheckBox) $("wallpaper_type_sexy")).setOnAction(event -> {
            boolean pressed = ((CheckBox) $("wallpaper_type_sexy")).isSelected();
            if (pressed) {
                ((Label) $("wallpaper_type_message")).setText("（非常不建议办公环境下勾选）");
                ((Label) $("wallpaper_type_message")).setTextFill(Paint.valueOf("#6CBB3C"));
                ((Label) $("wallpaper_type_message")).setVisible(true);
                ((Label) $("wallpaper_type_message")).setManaged(true);
            } else {
                ((Label) $("wallpaper_type_message")).setVisible(false);
                ((Label) $("wallpaper_type_message")).setManaged(false);
            }

        });
    }


    //壁纸刷新频率单选控制
    private void refreshFrequency() {
        ((RadioButton) $("refresh_frequency_3")).setOnAction(event -> {
            boolean pressed = ((RadioButton) $("refresh_frequency_3")).isSelected();
            if (pressed) {
                ((RadioButton) $("refresh_frequency_5")).setSelected(false);
                ((RadioButton) $("refresh_frequency_10")).setSelected(false);
                ((RadioButton) $("refresh_frequency_30")).setSelected(false);
            }

        });
        ((RadioButton) $("refresh_frequency_5")).setOnAction(event -> {
            boolean pressed = ((RadioButton) $("refresh_frequency_5")).isSelected();
            if (pressed) {
                ((RadioButton) $("refresh_frequency_3")).setSelected(false);
                ((RadioButton) $("refresh_frequency_10")).setSelected(false);
                ((RadioButton) $("refresh_frequency_30")).setSelected(false);
            }

        });
        ((RadioButton) $("refresh_frequency_10")).setOnAction(event -> {
            boolean pressed = ((RadioButton) $("refresh_frequency_10")).isSelected();
            if (pressed) {
                ((RadioButton) $("refresh_frequency_3")).setSelected(false);
                ((RadioButton) $("refresh_frequency_5")).setSelected(false);
                ((RadioButton) $("refresh_frequency_30")).setSelected(false);
            }

        });
        ((RadioButton) $("refresh_frequency_30")).setOnAction(event -> {
            boolean pressed = ((RadioButton) $("refresh_frequency_30")).isSelected();
            if (pressed) {
                ((RadioButton) $("refresh_frequency_5")).setSelected(false);
                ((RadioButton) $("refresh_frequency_10")).setSelected(false);
                ((RadioButton) $("refresh_frequency_3")).setSelected(false);
            }

        });
    }

    //是否清除已使用的壁纸单选控制
    private void isCleaningImages() {
        ((RadioButton) $("cleaning_images_no")).setOnAction(event -> {
            boolean pressed = ((RadioButton) $("cleaning_images_no")).isSelected();
            if (pressed) {
                ((RadioButton) $("cleaning_images_last_time")).setSelected(false);
                ((RadioButton) $("cleaning_images_three")).setSelected(false);
                ((RadioButton) $("cleaning_images_ten")).setSelected(false);
            }

        });
        ((RadioButton) $("cleaning_images_last_time")).setOnAction(event -> {
            boolean pressed = ((RadioButton) $("cleaning_images_last_time")).isSelected();
            if (pressed) {
                ((RadioButton) $("cleaning_images_no")).setSelected(false);
                ((RadioButton) $("cleaning_images_three")).setSelected(false);
                ((RadioButton) $("cleaning_images_ten")).setSelected(false);
            }

        });
        ((RadioButton) $("cleaning_images_three")).setOnAction(event -> {
            boolean pressed = ((RadioButton) $("cleaning_images_three")).isSelected();
            if (pressed) {
                ((RadioButton) $("cleaning_images_no")).setSelected(false);
                ((RadioButton) $("cleaning_images_last_time")).setSelected(false);
                ((RadioButton) $("cleaning_images_ten")).setSelected(false);
            }

        });
        ((RadioButton) $("cleaning_images_ten")).setOnAction(event -> {
            boolean pressed = ((RadioButton) $("cleaning_images_ten")).isSelected();
            if (pressed) {
                ((RadioButton) $("cleaning_images_no")).setSelected(false);
                ((RadioButton) $("cleaning_images_three")).setSelected(false);
                ((RadioButton) $("cleaning_images_last_time")).setSelected(false);
            }

        });
    }

    //壁纸更新时间单选控制
    private void imagesUpdateDate() {
        ((RadioButton) $("images_update_date_five")).setOnAction(event -> {
            boolean pressed = ((RadioButton) $("images_update_date_five")).isSelected();
            if (pressed) {
                ((RadioButton) $("images_update_date_ten")).setSelected(false);
                ((RadioButton) $("images_update_date_fifteen")).setSelected(false);
                ((RadioButton) $("images_update_date_thirty")).setSelected(false);
            }

        });
        ((RadioButton) $("images_update_date_ten")).setOnAction(event -> {
            boolean pressed = ((RadioButton) $("images_update_date_ten")).isSelected();
            if (pressed) {
                ((RadioButton) $("images_update_date_five")).setSelected(false);
                ((RadioButton) $("images_update_date_fifteen")).setSelected(false);
                ((RadioButton) $("images_update_date_thirty")).setSelected(false);
            }

        });
        ((RadioButton) $("images_update_date_fifteen")).setOnAction(event -> {
            boolean pressed = ((RadioButton) $("images_update_date_fifteen")).isSelected();
            if (pressed) {
                ((RadioButton) $("images_update_date_five")).setSelected(false);
                ((RadioButton) $("images_update_date_ten")).setSelected(false);
                ((RadioButton) $("images_update_date_thirty")).setSelected(false);
            }

        });
        ((RadioButton) $("images_update_date_thirty")).setOnAction(event -> {
            boolean pressed = ((RadioButton) $("images_update_date_thirty")).isSelected();
            if (pressed) {
                ((RadioButton) $("images_update_date_five")).setSelected(false);
                ((RadioButton) $("images_update_date_ten")).setSelected(false);
                ((RadioButton) $("images_update_date_fifteen")).setSelected(false);
            }

        });

    }

    /**
     * 文件选择样式逻辑
     */
    private void selectFolder() {
        ((Button) $("select_folder")).setOnAction(event -> {
            DirectoryChooser directoryChooser = new DirectoryChooser();
            File file = directoryChooser.showDialog(this);
            if (EmptyChecker.notEmpty(file)) {
                String path = file.getPath();//选择的文件夹路径
                //设置提示
                setFolderStyle(path, "#00ffff", "重新选择");
            }

        });
    }

    /**
     * 设置文件选择提示风格
     *
     * @param message
     * @param style
     * @param buttonName
     */
    private void setFolderStyle(String message, String style, String buttonName) {
        setErrorTip("select_folder_path", message);
        //设置提示颜色
        ((Label) $("select_folder_path")).setTextFill(Paint.valueOf(style));
        //设置不在隐藏
        ((Label) $("select_folder_path")).setVisible(true);
        ((Label) $("select_folder_path")).setManaged(true);

        ((Button) $("select_folder")).setLayoutX(distance(message));
        ((Button) $("select_folder")).setText(buttonName);
    }

    //点击文本打开网站
    public void openSourceURL(Application application) {
        ((Button) $("message1")).setOnAction(event ->
                application.getHostServices().showDocument("https://gitee.com/missyouch/desserts")
        );
        ((Button) $("message2")).setOnAction(event ->
                application.getHostServices().showDocument("https://gitee.com/missyouch/desserts")
        );

    }

    /**
     * 屏保单选逻辑
     */
    private void screenSaverSetUp() {
        ((RadioButton) $("screenSaver_no")).setOnAction(event -> {
            boolean pressed = ((RadioButton) $("screenSaver_no")).isSelected();
            if (pressed) {
                ((RadioButton) $("screenSaver_one")).setSelected(false);
                ((RadioButton) $("screenSaver_three")).setSelected(false);
                ((RadioButton) $("screenSaver_five")).setSelected(false);
            }

        });
        ((RadioButton) $("screenSaver_one")).setOnAction(event -> {
            boolean pressed = ((RadioButton) $("screenSaver_one")).isSelected();
            if (pressed) {
                ((RadioButton) $("screenSaver_no")).setSelected(false);
                ((RadioButton) $("screenSaver_three")).setSelected(false);
                ((RadioButton) $("screenSaver_five")).setSelected(false);
            }

        });
        ((RadioButton) $("screenSaver_three")).setOnAction(event -> {
            boolean pressed = ((RadioButton) $("screenSaver_three")).isSelected();
            if (pressed) {
                ((RadioButton) $("screenSaver_one")).setSelected(false);
                ((RadioButton) $("screenSaver_no")).setSelected(false);
                ((RadioButton) $("screenSaver_five")).setSelected(false);
            }

        });
        ((RadioButton) $("screenSaver_five")).setOnAction(event -> {
            boolean pressed = ((RadioButton) $("screenSaver_five")).isSelected();
            if (pressed) {
                ((RadioButton) $("screenSaver_one")).setSelected(false);
                ((RadioButton) $("screenSaver_three")).setSelected(false);
                ((RadioButton) $("screenSaver_no")).setSelected(false);
            }

        });
    }

    //计算像素点
    private double distance(String path) {
        double dd = 11.0;
        if (isContainChinese(path)) {
            dd = 17.0;
        }
        double dou = 125 + (path.length() * dd);
        return dou >= 395.0 ? 385.0 : dou;
    }

    //判断有无中文
    public static boolean isContainChinese(String str) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        return m.find();
    }

}
